package com.googlecode.sc2dm;

import android.content.Context;
import com.googlecode.sc2dm.annotations.scanner.AnnotationScanner;
import com.googlecode.sc2dm.integration.SC2DMReceiver;
import com.googlecode.sc2dm.log.Logger;
import com.googlecode.sc2dm.receiver.MessageReceiver;
import com.googlecode.sc2dm.register.DeviceRegistration;

import java.util.Arrays;
import java.util.List;

/**
 * @Author Jarle Hansen (jarle@jarlehansen.net)
 * Created: 9:01 PM - 9/13/11
 */
public class SC2DMPushMessages implements PushMessages {
    public static final String RECEIVER_NAME = SC2DMReceiver.class.getName();

    private final Context context;

    private boolean annotationScanComplete = false;
    private String packageName = "";

    public SC2DMPushMessages(Context context, String email) {
        this.context = context;

        DeviceRegistration deviceRegistration = new DeviceRegistration();
        MessageReceiver messageReceiver = new MessageReceiver();

        SC2DM.INSTANCE.setEmail(email);
        SC2DM.INSTANCE.setDeviceRegistration(deviceRegistration);
        SC2DM.INSTANCE.setMessageReceiver(messageReceiver);
    }

    public void registerCallbackClasses(Class<?>... classes) {
        annotationScanComplete = true;

        addAnnotatedClasses(Arrays.asList(classes));
    }

    public void scanPackage(String packageName) {
        Logger.i("Using automatic package scanning, package name: " + packageName);

        annotationScanComplete = true;

        AnnotationScanner annotationScanner = new AnnotationScanner(packageName);
        List<Class<?>> classes = annotationScanner.scan();

        addAnnotatedClasses(classes);
    }

    public void enable() {
        if (!annotationScanComplete) {
            scanPackage("");
        }

        SC2DM.INSTANCE.deviceRegistration().register(context, SC2DM.INSTANCE.email());
    }

    private void addAnnotatedClasses(List<Class<?>> classes) {
        SC2DM.INSTANCE.deviceRegistration().findAnnotations(classes);
        SC2DM.INSTANCE.messageReceiver().findAnnotations(classes);
    }
}
